package com.happok.onlineclass.usermanagement.user.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.happok.common.exception.NotFoundException;
import com.happok.common.exception.RepeatException;
import com.happok.onlineclass.usermanagement.common.dto.Contants;
import com.happok.onlineclass.usermanagement.common.exception.DisableException;
import com.happok.onlineclass.usermanagement.user.dao.UserDAO;
import com.happok.onlineclass.usermanagement.user.dataobject.UserDO;
import com.happok.onlineclass.usermanagement.user.dto.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 接口分类                        yapi 分类文件夹
 * 功能说明
 *
 * @author : chenac
 * @module 项目名称/模块名          yapi 项目组/子项目
 * @date : 2021/7/14 16:19
 */
@Service
public class UserDaoServiceImpl implements UserDaoService {

    @Autowired
    private UserDAO userDAO;

    @Override
    public UserDO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(UserDO::getPhone, username)
                .or()
                .eq(UserDO::getEmail, username);
        return userDAO.selectOne(queryWrapper);
    }

    @Override
    public void addUser(UserDO userDO) {
        try {
            BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
            userDO.setPassword(bcryptPasswordEncoder.encode(userDO.getPassword()));
            userDAO.insert(userDO);
        } catch (DuplicateKeyException dke) {
            if (dke.getCause().getMessage().contains(Contants.PHONE_UNIQUE)) {
                throw new RepeatException(3, "电话号码重复");
            } else if (dke.getCause().getMessage().contains(Contants.EMAIL_UNIQUE)) {
                throw new RepeatException(4, "邮箱重复");
            }
        }
    }

    @Override
    public void updateUserById(UserDO userDO) {
        try {
            if (!ObjectUtils.isEmpty(userDO.getPassword())) {
                BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
                userDO.setPassword(bcryptPasswordEncoder.encode(userDO.getPassword()));
            }
            userDAO.updateById(userDO);
        } catch (DuplicateKeyException dke) {
            if (dke.getCause().getMessage().contains(Contants.PHONE_UNIQUE)) {
                throw new RepeatException(3, "电话号码重复");
            } else if (dke.getCause().getMessage().contains(Contants.EMAIL_UNIQUE)) {
                throw new RepeatException(4, "邮箱重复");
            }
        }
    }

    @Override
    public void updateUserByUserId(Integer userId, String extendInfoId, ManageUpdateUserDTO manageUpdateUserDTO) {
        UserDO userDO = new UserDO();
        BeanUtil.copyProperties(manageUpdateUserDTO, userDO);
        LambdaUpdateWrapper<UserDO> updateWrapper = new LambdaUpdateWrapper<>();
        if (userDO.getEmail() == "") {
            updateWrapper.set(UserDO::getEmail, null);
        }
        if (userDO.getPhone() == "") {
            updateWrapper.set(UserDO::getPhone, null);
        }
        updateWrapper.eq(UserDO::getId, userId);
        userDO.setExtendInfoId(extendInfoId);
        try {
            userDAO.update(userDO, updateWrapper);
        } catch (DuplicateKeyException dke) {
            if (dke.getCause().getMessage().contains(Contants.PHONE_UNIQUE)) {
                throw new RepeatException(3, "电话号码重复");
            } else if (dke.getCause().getMessage().contains(Contants.EMAIL_UNIQUE)) {
                throw new RepeatException(4, "邮箱重复");
            }
        }
    }

    @Override
    public void enableUserByUserId(Integer userId, EnableUserDTO enableUserDTO) {
        UserDO userDO = new UserDO();
        userDO.setId(userId);
        userDO.setEnable(enableUserDTO.getEnable());
        userDAO.updateById(userDO);
    }

    @Override
    public void checkAccount(CheckAccountDTO checkAccountDTO) {
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(checkAccountDTO.getEmail())) {
            queryWrapper.eq(UserDO::getEmail, checkAccountDTO.getEmail());
        } else if (!ObjectUtils.isEmpty(checkAccountDTO.getPhone())) {
            queryWrapper.eq(UserDO::getPhone, checkAccountDTO.getPhone());
        }
        UserDO userDO = userDAO.selectOne(queryWrapper);
        if (!ObjectUtils.isEmpty(userDO)) {
            if (!ObjectUtils.isEmpty(checkAccountDTO.getPhone())) {
                throw new RepeatException(3, "电话号码重复");
            }
            if (!ObjectUtils.isEmpty(checkAccountDTO.getEmail())) {
                throw new RepeatException(4, "邮箱重复");
            }
        }
    }

    @Override
    public IPage<UserDO> listUser(ListUserParamDTO listUserParamDTO) {
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(listUserParamDTO.getEnable())) {
            queryWrapper.eq(UserDO::getEnable, listUserParamDTO.getEnable());
        }
        if (!ObjectUtils.isEmpty(listUserParamDTO.getUserIds())) {
            queryWrapper.in(UserDO::getId, listUserParamDTO.getUserIds());
        }
        if (!ObjectUtils.isEmpty(listUserParamDTO.getExcludeUserIds())) {
            queryWrapper.notIn(UserDO::getId, listUserParamDTO.getExcludeUserIds());
        }
        if (!ObjectUtils.isEmpty(listUserParamDTO.getNickName())
                || !ObjectUtils.isEmpty(listUserParamDTO.getPhone())
                || !ObjectUtils.isEmpty(listUserParamDTO.getEmail())) {
            queryWrapper.and(wrapper -> {
                if (!ObjectUtils.isEmpty(listUserParamDTO.getNickName())) {
                    wrapper.or().like(UserDO::getNickName, listUserParamDTO.getNickName());
                }
                if (!ObjectUtils.isEmpty(listUserParamDTO.getPhone())) {
                    wrapper.or().like(UserDO::getPhone, listUserParamDTO.getPhone());
                }
                if (!ObjectUtils.isEmpty(listUserParamDTO.getEmail())) {
                    wrapper.or().like(UserDO::getEmail, listUserParamDTO.getEmail());
                }
            });
        }
        queryWrapper.orderByDesc(UserDO::getCreateTime);
        Page<UserDO> page = new Page<>();
        if (!ObjectUtils.isEmpty(listUserParamDTO.getPage())) {
            page.setCurrent(listUserParamDTO.getPage());
        }
        if (!ObjectUtils.isEmpty(listUserParamDTO.getSize())) {
            page.setSize(listUserParamDTO.getSize());
        }
        return userDAO.selectPage(page, queryWrapper);
    }

    @Override
    public UserDO getUserDetailById(Integer userId) {
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDO::getId, userId);
        return userDAO.selectOne(queryWrapper);
    }

    @Override
    public void isUserExist(Integer userId) {
        UserDO userDO = getUserDetailById(userId);
        if (ObjectUtils.isEmpty(userDO)) {
            throw new NotFoundException(02, "用户不存在");
        }
    }

    @Override
    public String getHeadPortraitId(Integer userId) {
        return userDAO.getHeadPortraitId(userId);
    }

    @Override
    public void isUserEnable(Integer userId) {
        if (!userDAO.getUserEnable(userId)) {
            throw new DisableException("用户被禁用");
        }
    }

    @Override
    public List<UserSimpleDTO> listUser(List<Integer> userIds) {
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(userIds)) {
            queryWrapper.in(UserDO::getId, userIds);
            List<UserDO> userDOS = userDAO.selectList(queryWrapper);
            return BeanUtil.copyToList(userDOS, UserSimpleDTO.class);
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public List<ListUserDTO> listUserBasicInfo(List<Integer> userIds) {
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(userIds)) {
            queryWrapper.in(UserDO::getId, userIds);
            List<UserDO> userDOS = userDAO.selectList(queryWrapper);
            return BeanUtil.copyToList(userDOS, ListUserDTO.class);
        } else {
            return new ArrayList<>();
        }
    }
}